<template>
  <Dialog
    v-model="show"
    :title="props.data.id ? $t('attributeMana.编辑属性值') : $t('attributeMana.添加属性值')"
    width="500px"
    @confirm="handleConfirm"
    @close="handleClose"
  >
    <div>
      <LangTabs v-model="lang" />
      <el-form :model="form" label-width="160px" :rules="rules" ref="formRef">
        <el-form-item :label="$t('attributeMana.属性值')" :prop="'name' + lang">
          <el-input v-model="form['name' + lang]" :placeholder="$t('attributeMana.请输入属性值')" />
        </el-form-item>
        <el-form-item :label="$t('attributeMana.排序')" prop="sort">
          <el-input-number
              v-model="form.sort"
              :min="0"
              :max="999999999"
              :placeholder="$t('attributeMana.请输入排序')"
          />
        </el-form-item>
      </el-form>
    </div>
  </Dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import LangTabs from "@/components/LangTabs.vue";
import { setAttrLangs } from "@/i18n/tools";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();
const lang = ref(locale.value);
const show = defineModel("show", {
  type: Boolean,
  default: false,
});
const emit = defineEmits(["update:show", "refresh"]);
const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  parentAttributeId: {
    type: Number,
    default: 0,
  },
});

const formRef = ref(null);
const form = ref({
  sort: 0,
});

const rules = ref({});
setAttrLangs(form.value, "name", "");
setAttrLangs(rules.value, "name", {
  required: true,
  message: t("attributeMana.请输入属性值"),
  trigger: "blur",
});

watch(
  () => show.value,
  (newVal) => {
    if (newVal && props.data.id) {
      form.value = {
        ...props.data,
      };
    }
  }
);

const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      Api[props.data.id ? "skuAttributeDetail_edit" : "skuAttributeDetail_add"]({
        ...form.value,
        attributeId: props.parentAttributeId,
      }).then((res) => {
        if (res.status == 200) {
          ElMessage.success(t("attributeMana.操作成功"));
          handleClose();
          emit("refresh");
        }
      });
    }
  });
};
const handleClose = () => {
  formRef.value.resetFields();
  form.value = {
    name: "",
    sort: 0,
  };
  emit("update:show", false);
};
</script>
<style lang="scss" scoped></style>
